package org.csu.onlineedubackend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.csu.onlineedubackend.dto.StudentCountDTO;
import org.csu.onlineedubackend.entity.LessonProgress;

import java.util.List;

//教师端使用
@Mapper
public interface LessonProgressMapper extends BaseMapper<LessonProgress> {
    @Select("SELECT * FROM lesson_progress WHERE student_id = #{studentId}")
    List<LessonProgress> selectByStudentId(Integer studentId);

    /**
     * 根据学生ID和课时ID查询观看进度
     * @param studentId 学生ID
     * @param lessonId 课时ID
     * @return 课时观看进度记录
     */
    @Select("SELECT * FROM lesson_progress WHERE student_id = #{studentId} AND lesson_id = #{lessonId}")
    LessonProgress selectByStudentAndLesson(Integer studentId, Integer lessonId);

    @Select({
            "<script>",
            "SELECT * FROM lesson_progress",
            "WHERE student_id = #{studentId}",
            "AND lesson_id IN",
            "<foreach collection='lessonIds' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    List<LessonProgress> selectByStudentIdAndLessonIds(
            @Param("studentId") Integer studentId,
            @Param("lessonIds") List<Integer> lessonIds
    );

    // 统计所有已购课程下所有lesson_progress的 progress*lesson.duration 之和
    // Mapper方法
    @Select("""
        SELECT IFNULL(SUM(lp.progress * l.duration / 100), 0)
        FROM lesson_progress lp
        JOIN lesson l ON lp.lesson_id = l.id
        WHERE lp.student_id = #{studentId}
    """)
    Integer sumLearnMinutes(@Param("studentId") Integer studentId);

    // 3. 批量统计所有学生学习时长
    @Select("""
    SELECT lp.student_id, IFNULL(SUM(lp.progress * l.duration / 100), 0) AS count
    FROM lesson_progress lp
    JOIN lesson l ON lp.lesson_id = l.id
    GROUP BY lp.student_id
""")
    List<StudentCountDTO> sumLearnMinutesByStudentIds();
}


